#include "stm32f10x.h"                  // Device header
#include "delay.h"
#include "serial1.h"
#include "mqtt.h"
#include "string.h"
#include "led.h"
void DHT11_DQ_OUT(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOA,GPIO_Pin_11,(BitAction)BitValue);
}
uint8_t DHT11_DQ_IN(void)
{
	return GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_11);
}
void DHT11_OUT(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	GPIO_InitTypeDef GPIO_InitStruct;
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_Out_PP;
	GPIO_InitStruct.GPIO_Pin=GPIO_Pin_11;
	GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStruct);
	
}
void DHT11_IN(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	GPIO_InitTypeDef GPIO_InitStruct;
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_IPU;
	GPIO_InitStruct.GPIO_Pin=GPIO_Pin_11;
	GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStruct);
	
}
void DHT11_Start(void)
{
	DHT11_OUT();
	DHT11_DQ_OUT(0);
	Delay_ms(20);
	DHT11_DQ_OUT(1);
	Delay_us(30);
}
uint8_t DHT11_Check(void)
{
	uint8_t cnt=0;
	DHT11_IN();
	while(!DHT11_DQ_IN()&&cnt<100)
	{
		Delay_us(1);
		cnt++;
	}
	if(cnt>=100)
		return 1;
	else
		cnt=0;
	while(DHT11_DQ_IN()&&cnt<100)
	{
		Delay_us(1);
		cnt++;
	}
	if(cnt>=100)
		return 1;
	return 0;
}
uint8_t DHT11_Init(void)
{
	DHT11_Start();
	return DHT11_Check();
}
uint8_t DHT11_ReadBit(void)
{
	uint8_t cnt=0;
	//等待变为低电平
	while(DHT11_DQ_IN()==SET&&cnt<100)
	{
		Delay_us(1);
		cnt++;
	}
	cnt=0;
	//等待变为高电平
	while(DHT11_DQ_IN()==RESET&&cnt<100)
	{
		Delay_us(1);
		cnt++;
	}
	Delay_us(40);
	if(DHT11_DQ_IN()==SET)
		return 1;
	else
		return 0;
}
uint8_t DHT11_ReadByte(void)
{
	uint8_t temp=0x00;
	uint8_t i;
	for(i=0;i<8;i++)
	{
		if(DHT11_ReadBit()==SET)
			temp |= 0x80>>i;
	}
	return temp;
}
uint8_t DHT11_ReadData(uint8_t *temp0,uint8_t *temp1,uint8_t *humi0,uint8_t *humi1)
{
	uint8_t Array[5];
	uint8_t i;
	DHT11_Start();
	if(DHT11_Check()==0)
	{
		for(i=0;i<5;i++)
		{
			Array[i]=DHT11_ReadByte();
		}
		if(Array[0]+Array[1]+Array[2]+Array[3]==Array[4])
		{
			*humi0=Array[0];
			*humi1=Array[1];
			*temp0=Array[2];
			*temp1=Array[3];
			return 0;
		}
		else
		{
			Serial1_Printf("校验失败\r\n");
			return 1;
		}
	}
	Serial1_Printf("DHT11初始化失败\r\n");
	return 2;
}
void Sensor_DHT11(void)
{
	uint8_t temp;
	char temp01[256];
	uint8_t temper0;
	uint8_t temper1;
	uint8_t humi0;
	uint8_t humi1;
	temp=DHT11_ReadData(&temper0,&temper1,&humi0,&humi1);
	if(temp==0)
	{
		Serial1_Printf("temperature is %d.%d\r\n",temper0,temper1);
		Serial1_Printf("humidity is %d.%d\r\n\r\n",humi0,humi1);
		sprintf(temp01,"{\"method\":\"thing.event.property.post\",\"id\":\"00000001\",\"params\":{\"CurrentHumidity\":%d,\"CurrentTemperature\":%d.%d},\"version\":\"1.0.0\"}",humi0,temper0,temper1);
		MQTT_PublishQs0(Topic_Post,temp01,strlen(temp01));
	}
	else
	{
		Serial1_Printf("DHT11传感器读取失败\r\n");
	}
}
